<!--  -->
<template>
  <div>
    <!-- 面包屑区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->

      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model.value="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <template #append>
              <el-button icon="el-icon-search" @click="getUserList"></el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="adddialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="userlist.value" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template #default="scope">
            <el-switch
              v-model.value="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <!-- 编辑 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑"
              placement="top"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
            <!-- 分配权限 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" v-model="adddialogVisible" width="50%" 
        @close="addDialogClosed">
      <!-- 内容主体区 -->
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="70px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adddialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      v-model="editDialogVisible"
      @close="editDialogClosed"
      width="50%">
       <el-form
        :model="editForm.value"
        :rules="editFormrules"
        ref="editFormRef"
        label-width="70px"
        class="demo-ruleForm"
        
      >
      
        <el-form-item label="用户名">
          <el-input v-model="editForm.value.username" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.value.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.value.mobile"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editDialogVisible">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { reactive, ref, toRefs, onBeforeMount, onMounted } from 'vue'
import { UserList, changeUserState ,ReqaddUser,ReqEditUser} from '../../api/user.js'
import { ElMessage } from 'element-plus'
export default {
  name: 'user',
  data(){
    
    return {

    }
  },
  setup() {
    onBeforeMount(() => {})
    //用户传参
    const queryInfo = reactive({
      query: '',
      //当前的页数
      pagenum: 1,
      pagesize: 5
    })
    //用户列表
    const userlist = reactive([])
    // 总条数
    const total = ref(0)
    const getUserList = async () => {
      const res = await UserList(queryInfo)
      console.log(res)
      if (res.meta.status !== 200) return ElMessage.error('获取用户列表失败！')
      userlist.value = res.data.users
      total.value = res.data.total
      console.log(total.value)
    }
    //监听pa'gesize改变时间
    const handleSizeChange = newSize => {
      queryInfo.pagesize = newSize
      getUserList(queryInfo)
    }
    //监听页码值改变的事件
    const handleCurrentChange = newPage => {
      queryInfo.pagenum = newPage
      getUserList(queryInfo)
    }
    //监听swich改变

    const userStateChange = async userinfo => {
      const res = await changeUserState(userinfo)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return ElMessage.error('更新用户状态失败！')
      }
      ElMessage.success('更新用户状态成功！')
    }

    //控制添加 用户对话框的显示
    const adddialogVisible = ref(false)

    //添加用户的表单数据
    const addForm = reactive({
      username:'',
      password:'',
      email:'',
      mobile:''
    })
    //添加表单的验证规则对象
    const addFormrules = {
      username:[
        {required:true,message:'请输入用户名',trigger:'blur'},
        {min:3,max:10,message:'用户名长度在3-10个字符之间',trigger:'blur'}
      ],
      password:[
        {required:true,message:'请输入密码',trigger:'blur'},
        {min:6,max:15,message:'用户名长度在6-15个字符之间',trigger:'blur'}
      ],
      email:[
        {required:true,message:'请输入邮箱',trigger:'blur'},
        {pattern:/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message:'请输入正确的邮箱',trigger:'blur'}
      ],
      mobile:[
        {required:true,message:'请输入手机号',trigger:'blur'},
        {pattern:/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/, message:'请输入正确的手机号',trigger:'blur'}
      ]
    }
   
    const addFormRef = ref(null)
    //监听用户对话框的关闭事件
    const addDialogClosed = ()=>{
      addFormRef.value.resetFields()
    }

    //添加新用户
    const addUser = ()=>{
      addFormRef.value.validate(async valid =>{
        if(!valid) return
        //可以发起添加用户的网络请求
        const res = await ReqaddUser(addForm)
        if(res.meta.status !== 201) return ElMessage.error('添加用户失败')
        ElMessage.success('添加用户成功')
        adddialogVisible.value = false
        getUserList()
      })
    }

    //控制修改用户对话框的显示与隐藏
    const editDialogVisible = ref(false)

    //查询到的用户信息对象
    const editForm = reactive({})

    //展示编辑用户的对话框
    const showEditDialog = async (id)=>{
      console.log(id)
      const res = await ReqEditUser(id)
      if(res.meta.status !== 200) {
        return ElMessage.error('查询用户失败')
      }
      editForm.value = res.data
      editDialogVisible.value = true
    }
    //修改表单的校验规则
    //编辑表单的验证规则对象
    const editFormrules = {
      
      email:[
        {required:true,message:'请输入邮箱',trigger:'blur'},
        {pattern:/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message:'请输入正确的邮箱',trigger:'blur'}
      ],
      mobile:[
        {required:true,message:'请输入手机号',trigger:'blur'},
        {pattern:/^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/, message:'请输入正确的手机号',trigger:'blur'}
      ]
    }

    const editFormRef = ref(null)
    //监听修改用户对话框关闭事件
    const editDialogClosed = ()=>{
      console.log(editFormRef)
      editFormRef.value.resetFields()
    }
    //生命周期函数
    onMounted(() => {
      getUserList(queryInfo)
    })
    return {
      userlist,
      total,
      queryInfo,
      getUserList,
      handleSizeChange,
      handleCurrentChange,
      userStateChange,
      adddialogVisible,
      addForm,
      addFormrules,
      addFormRef,
      addDialogClosed,
      addUser,
      editDialogVisible,
      showEditDialog,
      editForm,
      editFormrules,
      editDialogClosed,
      editFormRef
    }
  }
}
</script>
<style scoped></style>
